<template>
  <div v-transfer-dom>
    <popup v-model="showPopup" :width="width" :height="height" :position="position" @on-hide="toggle(false)" @on-show="toggle(true)" class="search-popup">
      <search-header :searchPlaceHolder="searchPlaceholder" v-model.trim="seachValue" @submitSearch="submitSearch" @removeSearch="removeSearch">
        <p slot="button" @click="toggle(false)">取消</p>
      </search-header>

      <!-- 搜索首页 -->
      <template v-if="status === 0">
        <div class="searchBlock" v-if="searchHistory.length > 0">
          <p class="title">
            <span>搜索历史</span>
            <i @click="clearHistory" class="icon iconfont icon-delete-address" aria-hidden="true"></i>
          </p>
          <ul class="tags">
            <li v-for="(item, index) in searchHistory" :key="index" @click="clickTag(item)">{{item.length > 6 ? item.substring(0, 9) + '...' : item}}</li>
          </ul>
        </div>
        <div class="searchBlock" v-if="hotSearchList.length > 0">
          <p class="title">
            <span>Ta们都在搜~</span>
          </p>
          <ul class="tags">
            <li v-for="(item, index) in hotSearchList" :key="index" @click="clickTag(item)">{{item.length > 6 ? item.substring(0, 9) + '...' : item}}</li>
          </ul>
        </div>
      </template>
      <!-- 搜索结果页 -->
      <scroll v-else-if="status === 1" :data="searchList" v-cloak style="overflow: hidden;" :style="{height: SearchScrolllHeight + 'px'}" :bounce="false">
        <div class="search-scroll">
          <div class="searchBlock" v-if="touristTrack.length > 0">
            <p class="title">
              <span>智能路线推荐</span>
            </p>
            <ul class="search-result">
              <li v-for="item in touristTrack" :key="item.id" class="item">
                <p class="right" style=" font-size: 15px;">{{item.name}}</p>
                <div @click="toTouristTrack(item.id)" class="type"></div>
              </li>
            </ul>
          </div>
          <div class="searchBlock" v-if="searchList.length > 0">
            <p class="title">搜索结果</p>
            <ul class="search-result">
              <!-- <div @click="clickResultItem(item.id, item.type, item)">
                <cell :title="item.name" :inline-desc="item.intro" class="searchResultDesc"></cell>
              </div> -->
              <li v-for="item in searchList" :key="item.id" @click="clickResultItem(item.id, item.type, item)">
                <p class="name" v-html="item.nameHtml"></p>
                <p class="typeStr">{{item.typeStr}}</p>
              </li>
            </ul>
          </div>
          <not-data v-else-if="searchList.length == 0" tip="喔噢，没找到你搜索的数据~"></not-data>
        </div>
      </scroll>
    </popup>
  </div>
</template>

<script>
import { TransferDom, Popup } from 'vux'
import SearchHeader from '@/components/seach-header/seach-header'
import Scroll from '@/components/scroll/scroll'
import notData from '@/components/not-data/not-data'

import { isIphoneX } from '@/assets/js/brower'
import axios from '@/api/axiosApi'
import { localSearch } from '@/assets/js/local'
import { getRandomArrayElements } from '@/assets/js/utils'

const defaultTrack = [
  {
    id: '0',
    name: '西江千户苗寨'
  },
  {
    id: '1',
    name: '肇兴侗寨'
  }
]
const hotSearch = [
  '西江千户苗寨',
  '肇兴侗寨',
  '凯里',
  '自然风光',
  '古镇',
  '情侣游',
  '旅发大会',
  '文化旅游区',
  '黔东南美食',
  '景区特产',
  '特色酒店',
  '镇远',
  '丹寨',
  '剑河',
  '麻江',
  '黄平',
  '攻略',
  '少数民族文化',
  '苗寨',
  '侗族',
  '剑河温泉',
  '热门游记'
]

export default {
  model: {
    prop: 'value',
    event: 'toggle'
  },
  props: {
    value: Boolean,
    searchPlaceholder: {
      type: String,
      default: '请输入关键字搜索...'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '100%'
    },
    position: {
      type: String,
      default: 'right'
    },
    /**
     * 搜索所在的页面
     * ['all', 'cart', 'address', 'strategy']
     * 全部、商城、目的地、游记攻略。（默认全部）
     */
    type: {
      type: String,
      default: 'all'
    },
    /**
     * 搜索范围
     * 0 酒店 1 景区 2 特产 3 美食 4 游记 5攻略 6 动态
     */
    range: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      showPopup: this.value,
      seachValue: '',
      searchHistory: [],
      hotSearchList: [],
      searchList: [],
      touristTrack: [],
      status: 0 // 0 搜索进入页     1 搜索结果页
    }
  },
  directives: {
    TransferDom
  },
  components: {
    Popup,
    SearchHeader,
    Scroll,
    notData
  },
  created() {
    this.SearchScrolllHeight = window.innerHeight - 48 - 24
    if (isIphoneX()) {
      this.SearchScrolllHeight = window.innerHeight - 48 - 34
    }

    this.hotSearchList = getRandomArrayElements(hotSearch, 12)
    this.searchHistory = localSearch.get(this.type)
  },
  methods: {
    toggle(val) {
      this.status = 0
      this.seachValue = ''
      this.searchHistory = localSearch.get(this.type)
      this.searchList = []
      this.touristTrack = []
      this.$emit('toggle', val)
    },
    clearHistory() {
      localSearch.remove(this.type)
      this.searchHistory = localSearch.get(this.type)
    },
    clickTag(tag) {
      this.seachValue = tag
      this.submitSearch(tag)
    },
    removeSearch() {
      this.status = 0
      this.searchList = []
    },
    submitSearch(value) {
      this.status = 1
      if (value === '') {
        this.$vux.toast.text('请输入关键字搜索~', 'middle')
        return
      }
      // 智能路线
      const findIndex = defaultTrack.findIndex(item => {
        return item.name.indexOf(value) > -1
      })
      if (findIndex > -1) {
        this.touristTrack = [defaultTrack[findIndex]]
      } else {
        this.touristTrack = []
      }
      const tmp = []
      this.range.forEach(item => {
        tmp.push('type:' + item)
      })
      const params = `(${tmp.join(
        ' OR '
      )}) AND (name:${value} OR intro:${value})`
      console.log(params)
      axios.get(this, '/v1/query/' + params,
        {
          pageSize: 20
        },
        data => {
          // 0 酒店 1 景区 2 特产 3 美食 4 游记 5 攻略 6 动态 7 好友
          data.forEach(item => {
            switch (item.type) {
              case 0:
                item.typeStr = '酒店'
                break
              case 1:
                item.typeStr = '景区'
                break
              case 2:
                item.typeStr = '特产'
                break
              case 3:
                item.typeStr = '美食'
                break
              case 4:
                item.typeStr = '游记'
                break
              case 5:
                item.typeStr = '攻略'
                break
              case 6:
                item.typeStr = '动态'
                break
              case 7:
                item.typeStr = '好友'
                break
              default:
                item.typeStr = '其他'
            }
            item.nameHtml = item.name
            if (item.name && item.name.indexOf(value) > -1) {
              const name = item.name
              item.nameHtml = name.replace(value, `<span style="color: #00ceb9">${value}</span>`)
            }
          })
          localSearch.set(this.type, value)
          this.searchHistory = localSearch.get(this.type)
          this.searchList = data
          console.log(this.searchList)
        }
      )
    },
    clickResultItem(id, type, item) {
      switch (type) {
        case 0:
          this.$router.push(`/hotel/${id}`)
          break
        case 1:
          this.$router.push(`/scenic/${id}`)
          break
        case 2:
          this.$router.push(`/specialLocalProductDetail/${id}`)
          break
        case 3:
          this.$router.push(`/foodDetailsOne/${id}`)
          break
        case 4:
          this.$router.push(`/address/travels/${id}`)
          break
        case 5:
          this.$router.push(`/address/strategy/${id}`)
          break
        case 6:
          this.$router.push(`/meiTu/dynamicDesc/${id}`)
          break
        default:
          this.$vux.toast.text('该搜索迷失在太空里了~')
      }
      this.seachValue = ''
      this.toggle(false)
    },
    clickHistoryItem(item) {
      this.status = 0
      this.seachValue = item
      this.submitSearch(item)
    },
    toTouristTrack(id) {
      this.$router.push(`/home/touristTrack/${id}`)
      this.seachValue = ''
      this.toggle(false)
    }
  },
  watch: {
    value(val) {
      this.showPopup = val
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/css/variable.styl'
@import '~@/assets/css/mixins.styl'

.search-popup
  background #fff
.title
  line-height 1
  position relative
  padding-left 12px
  margin-bottom 12px
  font-size 15px
  color #999
  &:before
    content ''
    display block
    position absolute
    left 0
    top 0
    width 4px
    height 14px
    border-radius 5px
    background $color-theme
    overflow hidden
  i
    float right
    margin-right 3px
    font-size 16px
    color $color-theme
.searchBlock
  padding 0 16px
  padding-top 20px
  position relative
.tags
  li
    font-size 13px
    color #333
    height 22px
    line-height 23px
    border-radius 22px
    padding 0 12px
    border 0.5px solid #d0d0d0
    float left
    margin-right 12px
    margin-bottom 12px
  &:after
    display block
    content ''
    clear both
.search-result
  color #333
  li
    display flex
    align-items center
    justify-content space-between
    height 44px
    line-height 44px
    border-bottom 0.5px solid $color-border
    &:last-child
      border-bottom none
    .name
      font-size 14px
      width calc(100% - 50px)
      no-wrap()
      color #333
      span
        color $color-theme
    .typeStr
      width 50px
      no-wrap()
      font-size 12px
      color #999
      text-align right
.type
  width 40px
  min-width 40px
  height 40px
  background-size cover
  background-image url(../../assets/img/icon/luxian.png)
</style>
